import {createRouter, createWebHashHistory} from 'vue-router'
import NProgress from 'nprogress'

import 'nprogress/nprogress.css'
import {useAclStore, useOperatorStore} from "@/libs/store";
import {SysConfig} from "@/libs/config";
import {RouterUtil} from "@/utils";
import { INIT_ROUTER } from './constant'

NProgress.configure({easing: 'ease', showSpinner: false})
// 创建路由
const router = createRouter({
    history: createWebHashHistory(),
    routes: INIT_ROUTER,
    scrollBehavior() {
        return {
            el: '#app',
            top: 0,
            behavior: 'smooth',
        }
    },
})
// 定义拦截器
const interceptor = router => {
    // 路由进入前进行拦截
    router.beforeEach(async (to, from, next) => {
        const { getInitRouter } = useAclStore()
        const { hasLogin, hasInfo, getInfo } = useOperatorStore()
        const { whiteRoutes } = SysConfig
        if (whiteRoutes.includes(to.path)) {
            next()
        } else if (hasLogin) {
            if (!hasInfo) await getInfo()
            if (getInitRouter === false) {
                await RouterUtil.setupRouter()
                const firstPage = router.getRoutes().find(x => !x.name.startsWith('CONSTANT_'))
                if (to.path === '/' && firstPage !== undefined) next({ path: firstPage.path, replace: true })
                else next({ path: to.path, replace: true })
            } else next()
        } else {
            console.log("没有身份令牌 跳转到登录页")
            next(RouterUtil.toLoginRoute(to.path))
        }
    })
    // 路由结束后的处理
    router.afterEach(to => {
        window.document.title = to.meta.title
    })
}





// 封装一个路由安装方法
export const installRouter = app => {
    interceptor(router)
    app.use(router)
    return router
}


export default  router ;